from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework.viewsets import ModelViewSet
from goods.models import SKUImage, SKU
from meiduo_admin.my_paginate import MyPageNumberPagination
from meiduo_admin.serializer import sku_image_serializer
from rest_framework.response import Response

from meiduo_mall.utils.MyStorage import MyStorage


class SKUImageView(ModelViewSet):
    pagination_class = MyPageNumberPagination
    serializer_class = sku_image_serializer.SKUImageSerializer
    queryset = SKUImage.objects.all()

    def sku_simple(self, request):
        queryset = SKU.objects.all()
        serializer = sku_image_serializer.SKUSimpleSerializer(instance=queryset, many=True)


        return Response(serializer.data)

    def create(self, request, *args, **kwargs):
        sku_id = request.data.get("sku")
        image = request.data.get('image')

        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        image_url = MyStorage().save(None, image)
        if not image_url:
            return Response({"errmsg": "上传失败"}, status=400)

        # 3,4入库
        SKUImage.objects.create(sku_id=sku_id, image=image_url)
        return Response(status=201)

    def update(self, request, *args, **kwargs):
        image_obj = self.get_object()  # 根据pk,获取了图片对象
        image = request.data.get("image")
        sku_id = request.data.get("sku")

        # 2,获取序列化器校验数据
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        # 3,入库(上传图片)
        # 3,1上传图片
        image_url = MyStorage().save(None, image)
        if not image_url:
            return Response({"errmsg": "上传失败"}, status=400)

        # 3,4入库
        image_obj.image = image_url
        image_obj.sku_id = sku_id
        image_obj.save()

        # 4,返回响应
        return Response(status=201)





